package com.cskaoyan.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.cskaoyan.bean.*;
import com.cskaoyan.bean.vo.OrderDetailVo;
import com.cskaoyan.bean.vo.order.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.service.WXOrderService;
import com.cskaoyan.service.WXShoppingService;
import com.cskaoyan.utils.QueryUserIdByUserNameUtils;
import com.cskaoyan.utils.wx.OrderUtil;
import com.cskaoyan.utils.wx.UserUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.*;

/**
 * @title: WXOrderServiceImpl
 * @Author wangguangwu
 * @Description: 微信订单业务层的实现类
 * @Date: 2021/4/12 7:51 下午
 */
@Service
public class WXOrderServiceImpl implements WXOrderService {

    @Autowired
    CskaoyanmallOrderMapper orderMapper;

    @Autowired
    CskaoyanmallOrderGoodsMapper orderGoodsMapper;

    @Autowired
    CskaoyanmallUserMapper userMapper;
    @Autowired
    CskaoyanmallGoodsMapper goodsMapper;

    @Autowired
    CskaoyanmallCommentMapper commentMapper;
    @Autowired
    CskaoyanmallAddressMapper addressMapper;

    @Autowired
    CskaoyanmallCartMapper cartMapper;

    @Autowired
    CskaoyanmallCouponUserMapper couponUserMapper;

    @Autowired
    CskaoyanmallGoodsProductMapper goodsProductMapper;

    @Autowired
    CskaoyanmallSystemMapper systemMapper;

    @Autowired
    CskaoyanmallCouponMapper couponMapper;

    @Autowired
    WXShoppingService cartService;

    @Override
    public Integer count() {
        CskaoyanmallOrderExample example = new CskaoyanmallOrderExample();
        example.or().andDeletedEqualTo(false);
        long l = orderMapper.countByExample(example);
        return Convert.toInt(l);
    }


    @Override

    public Map<String, Object> orderList(Integer userId, String orderSn, List<Short> orderStatusArray, Integer page, Integer limit, String sort, String order) {

        PageHelper.startPage(page, limit);
        CskaoyanmallOrderExample orderExample = new CskaoyanmallOrderExample();

        CskaoyanmallOrderExample.Criteria criteria = orderExample.createCriteria();
        if (!ObjectUtils.isEmpty(userId)) {
            criteria.andUserIdEqualTo(userId);
        }

        if (!ObjectUtils.isEmpty(orderSn)) {
            criteria.andOrderSnEqualTo(orderSn);
        }


        if (!ObjectUtils.isEmpty(orderStatusArray)) {
            criteria.andOrderStatusIn(orderStatusArray);
        }
        criteria.andDeletedEqualTo(false);
        orderExample.setOrderByClause(sort + " " + order);


        List<CskaoyanmallOrder> orderwords = orderMapper.selectByExample(orderExample);
        PageInfo<CskaoyanmallOrder> pageInfo = new PageInfo<>(orderwords);
        long total = pageInfo.getTotal();

        Map<String, Object> res = new HashMap<>();
        res.put("items", orderwords);
        res.put("total", total);
        return res;

    }


    @Override
    public OrderDetailVo orderDetail(Integer id) {
        OrderDetailVo orderDetailVo = new OrderDetailVo();

        CskaoyanmallOrder order = orderMapper.selectByPrimaryKey(id);
        orderDetailVo.setOrder(order);

        CskaoyanmallOrderGoodsExample orderGoodsExample = new CskaoyanmallOrderGoodsExample();
        orderGoodsExample.createCriteria().andOrderIdEqualTo(id);
        List<CskaoyanmallOrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        orderDetailVo.setOrderGoods(orderGoods);

        CskaoyanmallUser user = userMapper.selectByPrimaryKey(order.getUserId());
        orderDetailVo.setUser(user);

        return orderDetailVo;
    }


    @Override
    public void addShipInfo(Integer orderId, String shipChannel, String shipSn) {
        orderMapper.addShipInfo(orderId, shipChannel, shipSn, new Date());

    }


    /**
     * 查询order中 user 订单的状态
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public Map<Object, Object> orderInfo(Integer userId) {
        CskaoyanmallOrderExample example = new CskaoyanmallOrderExample();
        example.or().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        List<CskaoyanmallOrder> orders = orderMapper.selectByExample(example);
        //待付款101
        int unpaid = 0;
        //待发货201
        int unship = 0;
        //待收货301
        int unrecv = 0;
        //未评论
        int uncomment = 0;

        for (CskaoyanmallOrder order : orders) {
            if (OrderUtil.isCreateStatus(order)) {
                unpaid++;
            } else if (OrderUtil.isPayStatus(order)) {
                unship++;
            } else if (OrderUtil.isShipStatus(order)) {
                unrecv++;
            } else if (OrderUtil.isConfirmStatus(order) || OrderUtil.isAutoConfirmStatus(order)) {
                uncomment += order.getComments();
            } else {
                // 什么事情都不用去做
            }
        }
        Map<Object, Object> orderInfo = new HashMap<>();
        orderInfo.put("unpaid", unpaid);
        orderInfo.put("unship", unship);
        orderInfo.put("unrecv", unrecv);
        orderInfo.put("uncomment", uncomment);

        return orderInfo;
    }


    /*
   *
   *操作的种类
   cancel;  //取消订单
   comment; //评论
   confirm; //确认收货
   delete; //删除订单
   pay;  //去付款
   rebuy; //再次购买
   refund; //退款
   *
   *
   * 每种状态对应的可选操作
   * 101 未付款              → 去付款 ，取消订单
   * 102 用户取消            → 删除订单
   * 103 系统取消            → 删除订单
   *
   * 201 已付款（未发货）    → 退款（不能取消订单）
   * 202 申请退款            → 订单取消，退款中
   * 203 已退款              → 删除订单
   *
   * 301 已发货（未收货）     → 确认收货，退款（不能取消订单）
   *
   * 401 用户收货            → 再次购买，(comments= 0 )评价，删除订单
   * 402 系统收货            → 再次购买，(comments= 0 )评价，删除订单
   *                           未评论  → 再次购买，评价，删除订单    *
   *
   * */
    @Override
    public WxOrderListVo wxOrderList(Integer showType, Integer page, Integer size) {
        //分页
        PageHelper.startPage(page, size);

        //showType=0 查询所有订单，否则查询对应订单
        CskaoyanmallOrderExample orderExample = new CskaoyanmallOrderExample();
        //从微信小程序中接收的初始订单状态为0、1、2、3、4
        // 0→所有未删除的订单
        //    * 1→待付款的订单  101
        //    * 2→待发货的订单  201
        //    * 3→待收货的订单  301
        //    * 4→待评价的订单  401 402
        if (showType != 0) {
            String orderStatus = showType + "01";
            //将orderStatus由String转化为与数据库匹配的short类型，添加条件andDeletedEqualTo(false)去与数据库遍历匹配
            orderExample.createCriteria().andOrderStatusEqualTo(Short.parseShort(orderStatus)).andDeletedEqualTo(false).andUserIdEqualTo(QueryUserIdByUserNameUtils.queryName(userMapper));
        } else {
            //否则显示所有订单信息
            orderExample.createCriteria().andDeletedEqualTo(false).andUserIdEqualTo(QueryUserIdByUserNameUtils.queryName(userMapper));
        }
        //查询得到所有订单数据

        List<CskaoyanmallOrder> orders = orderMapper.selectByExample(orderExample);

        //给List<WxOrderListDataBean> 内层data微信每条订单详细数据赋值
        ArrayList<WxOrderListDataBean> wxOrderListDataBeanList = new ArrayList<>();
        for (CskaoyanmallOrder order : orders) {
            WxOrderListDataBean wxOrderListDataBean = new WxOrderListDataBean();
            wxOrderListDataBean.setGroupin(false)
                    .setActualPrice(order.getActualPrice())
                    .setId(order.getId())
                    .setOrderSn(order.getOrderSn());

            //给OrderStatusText订单状态赋值
            Short status = order.getOrderStatus();
            //得到状态码对应的实际状态s
            String s = selectOrderStatusTextByStatus(status);
            wxOrderListDataBean.setOrderStatusText(s);

            //根据状态码判断选择怎样处理订单setHandleOption
            WxOrderHandleOption wxOrderHandleOption = selectHandleOptionByStatus(status);
            wxOrderListDataBean.setHandleOption(wxOrderHandleOption);


            //wxOrderListDataBean.setGoodsList
            ArrayList<WxOrderListGoodsListBean> orderWxListGoodsListBeans = new ArrayList<>();
            CskaoyanmallOrderGoodsExample orderGoodsExample = new CskaoyanmallOrderGoodsExample();
            //根据id来排序订单商品
            orderGoodsExample.createCriteria().andOrderIdEqualTo(order.getId());
            //查询得到所有订单商品数据
            List<CskaoyanmallOrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
            for (CskaoyanmallOrderGoods goods : orderGoods) {
                //新建一个订单商品对象，用于接收数据
                WxOrderListGoodsListBean wxOrderListGoodsListBean = new WxOrderListGoodsListBean();
                wxOrderListGoodsListBean.setGoodsName(goods.getGoodsName());
                wxOrderListGoodsListBean.setId(goods.getId());
                wxOrderListGoodsListBean.setNumber(goods.getNumber());
                wxOrderListGoodsListBean.setPicUrl(goods.getPicUrl());

                orderWxListGoodsListBeans.add(wxOrderListGoodsListBean);
            }
            wxOrderListDataBean.setGoodsList(orderWxListGoodsListBeans);
            wxOrderListDataBeanList.add(wxOrderListDataBean);
        }

        //给wxOrderListVo 外层data赋值
        //订单本身详细信息
        PageInfo<CskaoyanmallOrder> orderPageInfo = new PageInfo<>(orders);
        long total = orderPageInfo.getTotal();
        int pageNum = orderPageInfo.getPageNum();

        WxOrderListVo wxOrderListVo = new WxOrderListVo();
        wxOrderListVo.setCount(total);
        wxOrderListVo.setTotalPages(pageNum);
        wxOrderListVo.setData(wxOrderListDataBeanList);
        return wxOrderListVo;

    }

    //主要对状态OrderStatus进行操作
    @Override
    public OrderWxDetailRespVo wxOrderDetail(Integer oderId) {

        CskaoyanmallOrderGoodsExample orderGoodsExample = new CskaoyanmallOrderGoodsExample();
        //给orderGoodsExample根据oderId排序
        orderGoodsExample.createCriteria().andOrderIdEqualTo(oderId);
        //查找全部orderGoods,同一份订单可以有多个订单商品
        List<CskaoyanmallOrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);

        //一份订单只有一份信息，根据oderId获得
        CskaoyanmallOrder order = orderMapper.selectByPrimaryKey(oderId);
        //根据订单状态码，调用selectOrderStatusTextByStatus方法获得订单的文字状态
        String s = selectOrderStatusTextByStatus(order.getOrderStatus());
        order.setOrderStatusText(s);
//根据状态码调用方法selectHandleOptionByStatus，获得订单当前状态的下一步任务
        WxOrderHandleOption wxOrderHandleOption = selectHandleOptionByStatus(order.getOrderStatus());
        order.setHandleOption(wxOrderHandleOption);
//创建返回值对象orderWxDetailRespVo
        OrderWxDetailRespVo orderWxDetailRespVo = new OrderWxDetailRespVo();
        orderWxDetailRespVo.setOrderGoods(orderGoods);
        orderWxDetailRespVo.setOrderInfo(order);
        return orderWxDetailRespVo;
    }

    @Override
    public void wxOrderConfirm(Integer orderId) {
        //通过orderId查询订单
        CskaoyanmallOrder order = orderMapper.selectByPrimaryKey(orderId);

        order.setUpdateTime(new Date());
        Short status = 401;
        order.setOrderStatus(status);
        order.setComments((short) 1);
        order.setOrderStatusText(selectOrderStatusTextByStatus(order.getOrderStatus()));
        //updateByPrimaryKeySelective,只更新不为null的成员变量
        orderMapper.updateByPrimaryKeySelective(order);

    }


    @Override
    public WxOrderPreCommentVo wxOrderGoods(Integer orderId, Integer goodsId) {
        CskaoyanmallOrderGoodsExample orderGoodsExample = new CskaoyanmallOrderGoodsExample();
        orderGoodsExample.or().andOrderIdEqualTo(orderId).andGoodsIdEqualTo(goodsId);
        List<CskaoyanmallOrderGoods> orderGoodsList = orderGoodsMapper.selectByExample(orderGoodsExample);

        WxOrderPreCommentVo wxOrderPreCommentVo = new WxOrderPreCommentVo();

        for (CskaoyanmallOrderGoods orderGoods : orderGoodsList) {
            wxOrderPreCommentVo.setId(orderGoods.getId())
                    .setOrderId(orderGoods.getOrderId())
                    .setGoodsId(orderGoods.getGoodsId())
                    .setGoodsName(orderGoods.getGoodsName())
                    .setGoodsSn(orderGoods.getGoodsSn())
                    .setProductId(orderGoods.getProductId())
                    .setNumber(orderGoods.getNumber())
                    .setPrice(orderGoods.getPrice())
                    .setSpecifications(orderGoods.getSpecifications())
                    .setPicUrl(orderGoods.getPicUrl())
                    .setComment(orderGoods.getComment())
                    .setAddTime(orderGoods.getAddTime())
                    .setUpdateTime(orderGoods.getUpdateTime())
                    .setDeleted(orderGoods.getDeleted());
        }

        return wxOrderPreCommentVo;
    }

    /*
     * 1.创建订单表项和订单商品表项;
     * 2. 购物车清空;
     * 3. 优惠券设置已用;
     * 4. 商品货品库存减少;
     */
    @Override
    public Map<String, Object> wxOrderSubmit(OrderSubmitBo orderSubmitBo) {
        Map<String, Object> res = new HashMap<>();
        Integer userId = UserUtil.getUserId();
        Integer addressId = orderSubmitBo.getAddressId();
        Integer cartId = orderSubmitBo.getCartId();
        Integer couponId = orderSubmitBo.getCouponId();
        String message = orderSubmitBo.getMessage();

        List<CskaoyanmallCart> cartsList = cartService.getCheckedGoodsList(cartId, userId);
        CskaoyanmallAddress address = addressMapper.selectByPrimaryKey(addressId);
        CskaoyanmallCoupon coupon = couponMapper.selectByPrimaryKey(couponId);
        CskaoyanmallGoodsProduct goodsProduct = null;
        CskaoyanmallOrder order = new CskaoyanmallOrder();


        //减去数量
        for (CskaoyanmallCart cart : cartsList) {
            Short number = cart.getNumber();
            Integer goodsId = cart.getGoodsId();
            String[] specifications = cart.getSpecifications();
            CskaoyanmallGoodsProductExample goodsProductExample = new CskaoyanmallGoodsProductExample();
            goodsProductExample.or().andGoodsIdEqualTo(goodsId);
            List<CskaoyanmallGoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);


            for (CskaoyanmallGoodsProduct product : goodsProducts) {
                if (Arrays.equals(product.getSpecifications(), specifications)) {
                    goodsProduct = product;
                    if ((product.getNumber() - number) >= 0) {
                        goodsProduct.setNumber(product.getNumber() - number);

                        goodsProductMapper.updateByPrimaryKey(goodsProduct);
                    } else {
                        res.put("msg", "库存不足");
                        res.put("success", false);
                        return res;
                    }
                }
            }

            //判断是否有评论
            CskaoyanmallCommentExample commentExample = new CskaoyanmallCommentExample();
            commentExample.or().andValueIdEqualTo(cart.getGoodsId());
            long l = commentMapper.countByExample(commentExample);

            BigDecimal price = cart.getPrice();
            BigDecimal orderPrice = price.multiply(BigDecimal.valueOf(number));
            BigDecimal freight = null;
            if (orderPrice.compareTo(BigDecimal.valueOf(88)) > 0) {
                freight = BigDecimal.valueOf(0);
            } else {
                freight = BigDecimal.valueOf(10);
            }
            BigDecimal discount = null;
            if (!ObjectUtils.isEmpty(coupon)) {
                discount = coupon.getDiscount();

            }
            BigDecimal actualPrice = null;
            if (!ObjectUtils.isEmpty(discount)) {

                actualPrice = orderPrice.subtract(discount).add(freight);
            } else {
                actualPrice = orderPrice.add(freight);
            }
            Double aDouble = Convert.toDouble(actualPrice);
            order.setUserId(userId)
                    .setOrderSn(DateUtil.format(new Date(), "yyyyMMddHHmmss"))
                    .setOrderStatus((short) 101)
                    .setConsignee(address.getName())
                    .setMobile(address.getMobile())
                    .setAddress(address.getAddress())
                    .setMessage(message)
                    .setGoodsPrice(goodsProduct.getPrice())
                    .setFreightPrice(freight)
                    .setOrderPrice(orderPrice)
                    .setGrouponPrice(new BigDecimal(0))
                    .setIntegralPrice(new BigDecimal(0))
                    .setActualPrice(aDouble)
                    .setAddTime(new Date())
                    .setUpdateTime(new Date());

            if (l > 1) {
                order.setComments((short) 0);
            }
            if (!ObjectUtils.isEmpty(coupon)) {
                order.setCouponPrice(coupon.getDiscount());
            } else {
                order.setCouponPrice(new BigDecimal(0));
            }
            orderMapper.insertSelective(order);

            //将商品添加到order_goods
            CskaoyanmallOrderGoods orderGoods = new CskaoyanmallOrderGoods();
            orderGoods.setOrderId(order.getId())
                    .setGoodsId(cart.getGoodsId())
                    .setGoodsName(cart.getGoodsName())
                    .setGoodsSn(cart.getGoodsId())
                    .setProductId(cart.getProductId())
                    .setNumber(Convert.toInt(cart.getNumber()))
                    .setPrice(Convert.toInt(cart.getPrice()))
                    .setSpecifications(Convert.toStr(specifications))
                    .setPicUrl(goodsProduct.getUrl())
                    .setComment(0)
                    .setAddTime(new Date())
                    .setUpdateTime(new Date());
            orderGoodsMapper.insertSelective(orderGoods);

        }


        //设置优惠卷状态
        if (couponId != 0) {
            CskaoyanmallCouponUserExample couponUserExample = new CskaoyanmallCouponUserExample();
            couponUserExample.or().andUserIdEqualTo(userId).andCouponIdEqualTo(couponId);
            List<CskaoyanmallCouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);
            for (CskaoyanmallCouponUser couponUser : couponUsers) {
                couponUser.setStatus((short) 1)
                        .setUpdateTime(new Date());
                couponUserMapper.updateByPrimaryKey(couponUser);
            }
        }


        // 删除购物车里面的商品信息
        if (cartId.equals(0)) {
            cartService.clearGoods(userId);
        } else {
            cartService.deleteCart(cartId);
        }

        res.put("msg", "下单成功");
        res.put("success", true);
        res.put("order", order);

        return res;
    }

    @Override
    public void refundOrder(Integer orderId) {
        CskaoyanmallOrder order = new CskaoyanmallOrder();
        order.setOrderStatus(OrderStatusConstants.REQUEST_REFUND);
        order.setUpdateTime(new Date());
        //更新订单状态和updateTime
        updatebOrder(orderId, order);
        CskaoyanmallOrderGoodsExample orderGoodsExample = new CskaoyanmallOrderGoodsExample();
        orderGoodsExample.createCriteria().andOrderIdEqualTo(orderId);
        //获取订单商品列表
        List<CskaoyanmallOrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        for (CskaoyanmallOrderGoods orderGood : orderGoods) {
            CskaoyanmallGoodsProductExample goodsProductExample = new CskaoyanmallGoodsProductExample();
            goodsProductExample.createCriteria().andIdEqualTo(orderGood.getProductId());

            //获取订单中商品的库存
            int totalNum = goodsProductMapper.selectProductNumByExample(goodsProductExample);
            CskaoyanmallGoodsProduct goodsProduct = new CskaoyanmallGoodsProduct();
            goodsProduct.setNumber((orderGood.getNumber() + totalNum));
            //恢复对应商品的库存
            goodsProductMapper.updateByExampleSelective(goodsProduct, goodsProductExample);
        }

    }


    /**
     * 更新订单(因为订单的删除，修改，取消都要用到更新订单的方法)
     *
     * @param orderId
     * @param order
     * @return
     */
    //网上搜的
    public int updatebOrder(Integer orderId, CskaoyanmallOrder order) {
        CskaoyanmallOrderExample orderExample = new CskaoyanmallOrderExample();
        orderExample.createCriteria().andIdEqualTo(orderId);
        return orderMapper.updateByExampleSelective(order, orderExample);
    }

    //网上搜的
    public static class OrderStatusConstants {

        public final Short ORDER_UNPAID = 101;
        public final Short USER_CANCELLED = 102;
        public final Short SYSTEM_CANCELLED = 103;
        public final Short ORDER_PAID = 201;
        public static final Short REQUEST_REFUND = 202;
        public final Short ORDER_REFUNDED = 203;
        public final Short ORDER_SHIPPED = 301;
        public final Short USER_RECEIPT = 401;
        public final Short SYSTEM_RECEIPT = 402;
    }

    @Override
    public WxOrderCommentVo createGoodsComment(OrderWxCommentRequBo orderWxCommentRequBo) {

        //将评价更新插入到数据库
        CskaoyanmallComment comment = new CskaoyanmallComment();
        CskaoyanmallOrderGoods orderGoods = orderGoodsMapper.selectByPrimaryKey(orderWxCommentRequBo.getOrderGoodsId());
        comment.setValueId(orderGoods.getGoodsId());
        comment.setContent(orderWxCommentRequBo.getContent());
        comment.setUserId(UserUtil.getUserId());
        comment.setHasPicture(orderWxCommentRequBo.getHasPicture());
        comment.setPicUrls(orderWxCommentRequBo.getPicUrls());
        comment.setStar(orderWxCommentRequBo.getStar());
        comment.setAddTime(new Date());
        comment.setUpdateTime(new Date());
        commentMapper.insertSelective(comment);

        CskaoyanmallOrderGoods ordersGoods = new CskaoyanmallOrderGoods();
        ordersGoods.setComment(comment.getId());
        ordersGoods.setUpdateTime(new Date());
        ordersGoods.setId(orderWxCommentRequBo.getOrderGoodsId());
        orderGoodsMapper.updateByPrimaryKeySelective(ordersGoods);

//在orderExample1中添加未评价的条件
        CskaoyanmallOrderExample orderExample1 = new CskaoyanmallOrderExample();
        orderExample1.createCriteria().andOrderStatusEqualTo(Short.valueOf("401"));
//在orderExample2中添加未付款的条件
        CskaoyanmallOrderExample orderExample2 = new CskaoyanmallOrderExample();
        orderExample2.createCriteria().andOrderStatusEqualTo(Short.valueOf("101"));
//在orderExample3中添加未收货的条件
        CskaoyanmallOrderExample orderExample3 = new CskaoyanmallOrderExample();
        orderExample3.createCriteria().andOrderStatusEqualTo(Short.valueOf("301"));
//在orderExample4中添加未发货的条件
        CskaoyanmallOrderExample orderExample4 = new CskaoyanmallOrderExample();
        orderExample4.createCriteria().andOrderStatusEqualTo(Short.valueOf("201"));
//创建返回的数据对象wxOrderCommentVo，用以接收数据
        WxOrderCommentVo wxOrderCommentVo = new WxOrderCommentVo();
        //创建内层数据对象
        WxOrder wxOrder = new WxOrder();
        //给内层数据对象赋值
        wxOrder.setUncomment((int) orderMapper.countByExample(orderExample1))
                .setUnpaid((int) orderMapper.countByExample(orderExample2))
                .setUnrecv((int) orderMapper.countByExample(orderExample3))
                .setUnship((int) orderMapper.countByExample(orderExample4));

        //创建wxOrders数组来接收数据
        ArrayList<WxOrder> wxOrders = new ArrayList<>();

        //将内层数据对象加入数组中
        wxOrders.add(wxOrder);
        //将用以接收内层数据对象的数组加入返回对象wxOrderCommentVo中
        wxOrderCommentVo.setOrder(wxOrders);

        Integer orderGoodsId = orderWxCommentRequBo.getOrderGoodsId();
        CskaoyanmallOrderGoodsExample orderGoodsExample = new CskaoyanmallOrderGoodsExample();
        orderGoodsExample.or().andIdEqualTo(orderGoodsId);
        List<CskaoyanmallOrderGoods> orderGoodsList = orderGoodsMapper.selectByExample(orderGoodsExample);
        for (CskaoyanmallOrderGoods goods : orderGoodsList) {
            Integer orderId = goods.getOrderId();
            CskaoyanmallOrder order = new CskaoyanmallOrder();
            order.setComments((short) 0).setId(orderId);
            orderMapper.updateByPrimaryKeySelective(order);
        }
        return wxOrderCommentVo;

    }


    //根据状态码判断怎样处理订单
    private WxOrderHandleOption selectHandleOptionByStatus(Short status) {
        String s = String.valueOf(status);
        if ("101".equals(s)) {
            return WxOrderHandleOption.unpay();
        } else if ("201".equals(s)) {
            return WxOrderHandleOption.unship();
        } else if ("301".equals(s)) {
            return WxOrderHandleOption.unreceive();
        } else if ("401".equals(s)) {
            return WxOrderHandleOption.uncommentAndReceive();
        } else if ("402".equals(s)) {
            return WxOrderHandleOption.commentAndReceive();
        } else if ("102".equals(s) || "103".equals(s) || "203".equals(s)) {
            return WxOrderHandleOption.cancelledOrRefund();
        }
        return null;
    }


    //通过从数据库中得到的状态码，返回状态码对应的实际状态
    private String selectOrderStatusTextByStatus(Short status) {
        HashMap<String, String> orderStatuesMap = new HashMap<>();
        orderStatuesMap.put("101", "未付款");
        orderStatuesMap.put("102", "用户取消");
        orderStatuesMap.put("103", "系统取消");
        orderStatuesMap.put("201", "已付款");
        orderStatuesMap.put("202", "申请退款");
        orderStatuesMap.put("203", "已退款");
        orderStatuesMap.put("301", "已发货");
        orderStatuesMap.put("401", "用户收获");
        orderStatuesMap.put("402", "系统收获");
        String s = orderStatuesMap.get(String.valueOf(status));
        return s;
    }

    @Override
    public void cancelOrderById(Integer orderId) {

        CskaoyanmallOrder order = new CskaoyanmallOrder();
        order.setOrderStatus(OrderStatusConstants.REQUEST_REFUND);
        order.setUpdateTime(new Date());
        //更新订单状态和updateTime
        updatebOrder(orderId, order);

        order.setOrderStatus((short) 102);

        order.setId(orderId);
        orderMapper.updateByPrimaryKeySelective(order);

//网上搜的可以更新库存代码，不想写了
        CskaoyanmallOrderGoodsExample orderGoodsExample = new CskaoyanmallOrderGoodsExample();
        orderGoodsExample.createCriteria().andOrderIdEqualTo(orderId);
        //获取订单商品列表
        List<CskaoyanmallOrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        for (CskaoyanmallOrderGoods orderGood : orderGoods) {
            CskaoyanmallGoodsProductExample goodsProductExample = new CskaoyanmallGoodsProductExample();
            goodsProductExample.createCriteria().andIdEqualTo(orderGood.getProductId());

            //获取订单中商品的库存
            int totalNum = goodsProductMapper.selectProductNumByExample(goodsProductExample);
            CskaoyanmallGoodsProduct goodsProduct = new CskaoyanmallGoodsProduct();
            goodsProduct.setNumber((orderGood.getNumber() + totalNum));
            //恢复对应商品的库存
            goodsProductMapper.updateByExampleSelective(goodsProduct, goodsProductExample);
        }

    }

    @Override
    public void deleteOrderById(Integer orderId) {
        CskaoyanmallOrder order = new CskaoyanmallOrder();
        order.setOrderStatus(OrderStatusConstants.REQUEST_REFUND);
        order.setUpdateTime(new Date());
        //更新订单状态和updateTime

        updatebOrder(orderId, order);
        order.setId(orderId);
        order.setDeleted(true);
        orderMapper.updateByPrimaryKeySelective(order);

        //网上搜的可以更新库存代码，不想写了
        CskaoyanmallOrderGoodsExample orderGoodsExample = new CskaoyanmallOrderGoodsExample();
        orderGoodsExample.createCriteria().andOrderIdEqualTo(orderId);
        //获取订单商品列表
        List<CskaoyanmallOrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        for (CskaoyanmallOrderGoods orderGood : orderGoods) {
            CskaoyanmallGoodsProductExample goodsProductExample = new CskaoyanmallGoodsProductExample();
            goodsProductExample.createCriteria().andIdEqualTo(orderGood.getProductId());

            //获取订单中商品的库存
            int totalNum = goodsProductMapper.selectProductNumByExample(goodsProductExample);
            CskaoyanmallGoodsProduct goodsProduct = new CskaoyanmallGoodsProduct();
            goodsProduct.setNumber((orderGood.getNumber() + totalNum));
            //恢复对应商品的库存
            goodsProductMapper.updateByExampleSelective(goodsProduct, goodsProductExample);
        }

    }


    @Override
    public void setStatusPaid(Integer orderId) {
        CskaoyanmallOrderExample example = new CskaoyanmallOrderExample();
        example.or().andIdEqualTo(orderId).andUserIdEqualTo(UserUtil.getUserId());
        List<CskaoyanmallOrder> orders = orderMapper.selectByExample(example);
        for (CskaoyanmallOrder order : orders) {
            order.setOrderStatus((short) 201);
            orderMapper.updateByPrimaryKey(order);
        }
    }


}
